import {AnyAction, Reducer} from 'redux';
import {EffectsCommandMap} from 'dva';
import {addAndUpdate, fetchDetail} from "./service";
import {message} from "antd";
import {IAdmin} from "../data";
import router from "umi/router";
import {IRole} from "@/pages/account/role/data";

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & { select: <T>(func: (state: {}) => T) => T },
) => void;

export interface ModelState {
  detail: IAdmin;
  roles: IRole[]
}

export interface ModelType {
  namespace: string;
  state: ModelState;
  effects: {
    fetchDetail: Effect;
    addAndUpdate: Effect;
  };
  reducers: {
    saveDetail: Reducer<{}>;
  };
}

const Model: ModelType = {
  namespace: 'adminSave',

  state: {
    detail: {},
    roles: []
  },

  effects: {

    * fetchDetail({payload}, {call, put}) {
      const response = yield call(fetchDetail, payload);
      yield put({
        type: 'saveDetail',
        payload: response
      })
    },
    * addAndUpdate({payload}, {call, put}) {
      const response = yield call(addAndUpdate, payload);
      if (response.status === 'ok') {
        message.success('操作成功');
        setTimeout(() => {
          router.push('/account/admin/list');
        }, 1000)
      } else {
        message.error(response.message);
      }
    },
  },

  reducers: {
    saveDetail(state, action) {
      return {
        ...state,
        detail: action.payload.data,
        roles: action.payload.roles
      };
    },
  },
};

export default Model;
